#include "GeomSphere.h"
extern unsigned int load_texture(char *filename);

GeomSphere::GeomSphere(Vec3d _center, double _radius): mRadius(_radius){
	for(int i=0; i<3; i++) mTransform[i][3]=_center[i];
	mType=SPHERE;
	mFirstDraw = true;
}

// Transform the sphere by the inverse of Matrix
GeomObject* GeomSphere::getObjApplyInvTransform(const Mat4d &_mat){ 
	Vec3d t(_mat[0][3], _mat[1][3], _mat[2][3]);
	Vec3d center = getCenter() - t;

	return new GeomSphere(center, mRadius);
}

void GeomSphere::draw(Vec4d _color, bool _default){
	Vec4d col = _default? mColor : _color;
	glColor4dv( col.Ref() );

	static bool firstCall=true;
	if(mFirstDraw){
		mFirstDraw=false;
		//if(mTextureFileName) mTexture = load_texture(mTextureFileName);
	}
	//glPushMatrix();
	//getGLTransform();
	//glMultMatrixd(mGLTransMat);
	//glScalef(mRadius, mRadius, mRadius);
	//glutSolidSphere(1.0, 16, 16);
	//glPopMatrix();

	//glDepthFunc(GL_LEQUAL);
	//glEnable(GL_CULL_FACE);
	//glDisable(GL_DEPTH_TEST);

	glDisable(GL_CULL_FACE);
	GLUquadric *sphere = gluNewQuadric();
	if(mTextureFileName){
		glColor4d(1,1,1,1);	// white base for the texture
		glEnable(GL_TEXTURE_2D);
	}
	glPushMatrix();
	getGLTransform();
	glMultMatrixd(mGLTransMat);
	glScalef(mRadius, mRadius, mRadius);
	if(mTextureFileName){
		glBindTexture(GL_TEXTURE_2D, mTexture);
		glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
		gluQuadricTexture(sphere, true);
	}
	gluSphere(sphere, 1.0, 20, 20);
	glPopMatrix();
	gluDeleteQuadric(sphere);
	if(mTextureFileName){
		glDisable(GL_TEXTURE_2D);
	}
	glEnable(GL_CULL_FACE);
}
